//
//  WeightScalePickerViewController.m
//  IWeighMyself
//
//  Created by Francisco Gindre on 8/12/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "WeightScalePickerViewController.h"


@implementation WeightScalePickerViewController
@synthesize weightPicker;
@synthesize appDelegate;
@synthesize newWeightView;
@synthesize aTableView;
@synthesize button;
@synthesize weightCell;
#pragma mark -
#pragma mark Constants

#define PICKER_ROW_HEIGHT 40
#define PICKER_COMPONENTS 2
#define UNIT_COMPONENT_WIDTH 240.0
#define DECIMAL_COMPONENT_WIDTH 40
#define PICKER_WIDTH 240
#define DECIMAL_COMPONENT 1
#define UNIT_COMPONENT 0
#define MAX_WEIGHT_POUNDS 400
#define MAX_WEIGHT_KILOS 200


#pragma mark -
#pragma mark View life cycle

-(id)initWithWeightAndParentView: (Weight*)aWeight parentView:(LogNewWeightViewController*)logNewWeightView {
	
	self = [[WeightScalePickerViewController alloc] initWithNibName:@"WeightScalePickerViewController" bundle:nil];
	if (self){
		/*
		 set the attributes of this view controller
		 */
		weight = [aWeight retain];
		newWeightView = [logNewWeightView retain];
		
		weightCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] ;
		
		/*
		 select unit
		 */
		
		NSString *unit;
		if ([appDelegate isKilosWeightSelectedUnit]) {
			unit = NSLocalizedString(@"WeightUnitKilos",@"");
			[weightCell.textLabel setText:[NSString stringWithFormat:@"%.1f %s",[aWeight weightInKilos],[unit UTF8String]]];
		}
		else {
			unit = NSLocalizedString(@"WeightUnitPounds",@"");
			[weightCell.textLabel setText:[NSString stringWithFormat:@"%.1f %s",[aWeight weightInPounds],[unit UTF8String]]];
		}
		
			
	
		
	}
	return self;
}
/*
 
 
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.appDelegate = [[UIApplication sharedApplication]delegate];
	
	[self setTitle:NSLocalizedString(@"WeightPickerTitle",@"")];
	
	self.button = [[UIBarButtonItem alloc]initWithTitle:NSLocalizedString(@"DoneButtonTitle",@"") 
															  style:UIBarButtonItemStyleDone
															 target:self
															 action:@selector(doneAction:)];
	[self.button retain];
	
	[self.aTableView reloadData];
	
	//[button release];
	
	
	
	[weightPicker setShowsSelectionIndicator:YES];
	if([appDelegate isKilosWeightSelectedUnit]){
		[weightPicker selectRow:[[weight getUnitsInKilos]intValue] inComponent:UNIT_COMPONENT animated:YES];
		[weightPicker selectRow:[[weight getDecimalInKilos]intValue] inComponent:DECIMAL_COMPONENT animated:YES];
	}else {
		[weightPicker selectRow:[[weight getUnitsInPounds]intValue] inComponent:UNIT_COMPONENT animated:YES];
		[weightPicker selectRow:[[weight getDecimalInPounds]intValue] inComponent:DECIMAL_COMPONENT animated:YES];			
	}
	/*
	UITableViewCell *cell;
	cell = [self.aTableView cellForRowAtIndexPath:[NSIndexPath indexPathWithIndex:0]];
	
	if([appDelegate isKilosWeightSelectedUnit]){
		[cell.textLabel setText:[NSString stringWithFormat:@"%.1f",weight.weightInKilos]];
	}else {
		[cell.textLabel setText:[NSString stringWithFormat:@"%.1f",weight.weightInPounds]];
		
	}

	[aTableView reloadData];
	[cell release];
	 */
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark UIPickerViewDelegate



/*
 Called by the picker view when the user selects a row in a component.
 */
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	// report the selection
	//NSLog(@"Selectedrow didSelectRow %d in component %d",row,component);
	[self.aTableView reloadData];
	if (self.navigationItem.rightBarButtonItem ==nil) {
		
	
		self.navigationItem.rightBarButtonItem = button;
	}
}
#pragma mark -
#pragma mark UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{	
	
	return [NSString stringWithFormat:@"%d",row];
	
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
	
	if (component == 0)
		componentWidth = UNIT_COMPONENT_WIDTH;	// first column size is wider to hold names
	else
		componentWidth = DECIMAL_COMPONENT_WIDTH;	// second column is narrower to show numbers
	
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return PICKER_ROW_HEIGHT;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	switch (component) {
		case UNIT_COMPONENT:
			if ([appDelegate isKilosWeightSelectedUnit]) {
				return MAX_WEIGHT_KILOS;
			}
			else {
				return MAX_WEIGHT_POUNDS;
			}

			break;
		case DECIMAL_COMPONENT:
			return 10;
			break;

		
	}
	return 2;//shouldn't get here
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return PICKER_COMPONENTS;
}

/* 
 converts the value selected in the weight picker into a float value.
 */
-(float)pickerToFloat{

	float decimal = (float)[weightPicker selectedRowInComponent:DECIMAL_COMPONENT]*0.1;

	float units = (float)[weightPicker selectedRowInComponent:UNIT_COMPONENT];

	return (float)(decimal+units);
}

#pragma mark -
#pragma mark DoneButton action handling

-(void)doneAction:(id)sender {
	

	if([appDelegate isKilosWeightSelectedUnit]) {
		[newWeightView.currentEntry setWeightInKilos:[NSNumber numberWithFloat:[self pickerToFloat]]];
	}
	else {
		[newWeightView.currentEntry setWeightInPounds:[NSNumber numberWithFloat:[self pickerToFloat]]];
	}

	
	
	[self.navigationController popViewControllerAnimated:YES];
	[newWeightView.tableView reloadData];
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
    
    if (weightCell == nil) {
        weightCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
    }
    */
    // Configure the cell...
    NSString *unit;
	
	//Select the unit to be displayed
	
	if ([appDelegate isKilosWeightSelectedUnit]) {
		unit = NSLocalizedString(@"WeightUnitKilos",@"");
	}
	else {
		unit = NSLocalizedString(@"WeightUnitPounds",@"");
	}
	
	if ([self pickerToFloat]) {
		
	
		[self.weightCell.textLabel setText:[NSString stringWithFormat:@"%.1f %s",[self pickerToFloat],[unit UTF8String]]];
	}else {
		if([appDelegate isKilosWeightSelectedUnit])
		{
			[self.weightCell.textLabel setText:[NSString stringWithFormat:@"%.1f %s",[weight.weightInKilos floatValue],[unit UTF8String]]];
		}
		else {
			[self.weightCell.textLabel setText:[NSString stringWithFormat:@"%.1f %s",[weight.weightInPounds floatValue],[unit UTF8String]]];
		}

	}

    return weightCell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return NSLocalizedString(@"WeightPickerSection",@"");
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}


@end
